package top.lingkang.ciyuanwaf.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lingkang
 * created by 2023/11/24
 */
@Slf4j
public class CommonUtils {
    public static File getItem(File file, String name, boolean isDirectory) {
        for (File val : file.listFiles()) {
            if (val.getName().equals(name)) {
                if (isDirectory) {
                    if (val.isDirectory())
                        return val;
                } else
                    return val;
            }
        }
        return null;
    }

    public static String[] getFileListName(File file) {
        return getFileListName(file, false);
    }

    public static String[] getFileListName(File file, boolean isFolder) {
        List<String> list = new ArrayList<>();
        File[] files = file.listFiles();
        if (files != null)
            for (File f : files) {
                if (isFolder) {
                    if (f.isDirectory())
                        list.add(f.getAbsolutePath());
                } else list.add(f.getAbsolutePath());
            }
        return list.toArray(new String[0]);
    }

    public static String md5(String str) {
        try {
            // Static getInstance method is called with hashing MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(str.getBytes());

            // Convert byte array into signum representation
            BigInteger no = new BigInteger(1, messageDigest);

            // Convert message digest into hex value
            String hashtext = no.toString(16);

            // Pad with leading zeros  在结果字符串前面补0，使其达到32位
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

}
